// pages/search/index.js
import { formatDate } from '../../utils/util'
const app = getApp()

Page({

  data: {
    isExpense: 'true',
    isLoad: false,
    isMore: false,

    allData: [],

    searchType: '',
    searchStartDt: '',
    searchEndDt: '',
    findList: [],
    totalMoney: 0,
    recordCount: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let d = new Date()
    d.setDate(1)
    var startDt = formatDate(d)
    d.setDate(new Date(d.getFullYear(), d.getMonth() + 1, 0).getDate())
    var endDt = formatDate(d)

    this.setData({
      isExpense: options.isExpense || 'true',
      searchStartDt: startDt,
      searchEndDt: endDt
    })
  },
  onShow: function () {
    this.loadData()
  },
  loadData() {
    if (this.data.searchType.length > 0) {
      this.setData({
        isLoad: true
      })
      app.post({
        action: 'getExpenseList',
        data: {
          isExpense: this.data.isExpense,
          type: this.data.searchType,
          startDt: this.data.isMore ? this.data.searchStartDt : '',
          endDt: this.data.isMore ? this.data.searchEndDt : ''
        }
      }).then(res => {
        let count = 0, sum = 0
        res.data.forEach(item => {
          count++;
          item.money = (+item.money).toFixed(2)
          sum += +item.money
        })
        this.setData({
          isLoad: false,
          allData: res.data,
          findList: res.data,
          totalMoney: sum.toFixed(2),
          recordCount: count
        })
      }).catch(res => {
        this.setData({
          isLoad: false,
          allData: [],
          findList: [],
          totalMoney: 0,
          recordCount: 0
        })
      })
    } else {
      this.setData({
        isLoad: false,
        allData: [],
        findList: [],
        totalMoney: 0,
        recordCount: 0
      })
    }
  },
  searchTypeInput(e) {
    this.setData({ searchType: e.detail.value })
  },
  startDateChange(e) {
    this.setData({ searchStartDt: e.detail.value })
  },
  endDateChange(e) {
    this.setData({ searchEndDt: e.detail.value })
  },
  search(e) {
    this.loadData()
  },
  more(e) {
    this.setData({
      isMore: !this.data.isMore
    })
  }
})